package com.example.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.entity.Role;
import com.example.demo.entity.Student;
import com.example.demo.entity.common.CommonResult;
import com.example.demo.service.RoleService;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 角色表(Role)表控制层
 *
 * @author makejava
 * @since 2020-06-05 10:36:52
 */
@Controller
@RequestMapping("role")
public class RoleController {
    /**
     * 服务对象
     */
    @Resource
    @Autowired
    private RoleService roleService;

    @PostMapping("deleteById")
    @ResponseBody
    public boolean deleteById(Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return false;
        }
        System.out.println(ids);
        roleService.deleteById(Arrays.asList(ids));
        return true;
    }

    @PostMapping("deleteById1")
    @ResponseBody
    public boolean deleteById1(Integer id) {
        System.out.println("删除单条角色数据");
        if ( id == null) {
            return false;
        }
        System.out.println(id);
        return roleService.deleteById1(id);
    }

    @PostMapping("queryAll")
    @ResponseBody
    public Object queryAll(Integer page, Integer limit, Role bean) {
        System.out.println(bean);
        CommonResult<Role> result = new CommonResult<>();
        IPage<Role> ipage = roleService.queryAllByLimit(page, limit, bean);
        result.setCode(0);
        result.setCount(ipage.getTotal());
        result.setData(ipage.getRecords());
        System.out.println("角色数据查询成功");
        System.out.println(result);
        return result;
    }

    @RequestMapping("save")
    @ResponseBody
    public Object save(Role bean) {
        System.out.println("修改和添加角色数据");
        System.out.println("ID为："+bean.getId());
        boolean result = false;
        //判断账号是否存在
        //判断是添加还是修改
        if (bean.getId() != null) {
            result = roleService.update(bean) > 0;
        } else {
            result = roleService.insert(bean).getName() != null;
        }
        return result;
    }

    @RequestMapping("toList")
    public String toList() {
        return "menu/role_list";
    }

    @RequestMapping("toEdit")
    public String toEdit(Integer id, Model model){
        Role bean = roleService.queryById(id);
        model.addAttribute("bean",bean);
        return "menu/role_add";
    }

    @RequestMapping("toAdd")
    public String toAdd(Model model){
        model.addAttribute("bean",new Role());
        return "menu/role_add";
    }

}